<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="资产设备名称" prop="assetName">
        <el-select
          v-model="queryParams.assetName"
          placeholder="请选择资产设备名称"
          clearable
          @change="handleQuery"
          style="width: 220px;"
        >
          <el-option
            v-for="(name, index) in uniqueAssetNames"
            :key="`${name}-${index}`"
            :label="name"
            :value="name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="移动时间范围">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 320px;"
          @clear="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equ:repair:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equ:repair:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equ:repair:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equ:repair:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维修工单id" align="center" prop="repairId" />
      <el-table-column label="资产设备名称" align="center" prop="assetName"/>
      <el-table-column label="工单最终状态" align="center" prop="orderStatus" />
      <el-table-column label="工单闭环时间" align="center" prop="closeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.closeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equ:repair:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equ:repair:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="view-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修工单id" prop="repairId">
              <el-input v-model="form.repairId" placeholder="请输入维修工单id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产设备id" prop="assetId">
              <el-input v-model="form.assetId" />
            </el-form-item>
          </el-col>

          <!-- 使用 JSON 编辑器替换动态表格 -->
          <el-col :span="24">
            <el-form-item label="故障信息" prop="faultInfo">
              <vue-json-editor
                v-model="form.faultInfo"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="维修执行信息" prop="repairExec">
              <vue-json-editor
                v-model="form.repairExec"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="维修验收结果" prop="repairCheck">
              <vue-json-editor
                v-model="form.repairCheck"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="附件链接" prop="fileUrls">
              <file-upload v-model="form.fileUrls"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单闭环时间" prop="closeTime">
              <el-date-picker clearable
                              v-model="form.closeTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择工单闭环时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueJsonEditor from 'vue-json-editor';
import { listRepairVo, getRepair, delRepair, addRepair, updateRepair } from "@/api/equ/repair";
import { getAllAssetName } from "@/api/equ/asset";

export default {
  name: "Repair",
  components: { VueJsonEditor },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      repairList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetName: null,
        timeRange: null,
      },
      form: {
        repairId: null,
        assetId: null,
        faultInfo: {},
        repairExec: {},
        repairCheck: {},
        orderStatus: null,
        closeTime: null,
        fileUrls: null,
        remark: null
      },
      uniqueAssetNames: [],
      rules: {
        repairId: [
          { required: true, message: "维修工单id不能为空", trigger: "blur" }
        ],
        assetId: [
          { required: true, message: "资产设备id不为空", trigger: "blur" }
        ]
      },
      jsonEditorOptions: {
        mode: 'form',
        expanded: true,
        showBtn: false,
        indentation: 2,
        mainMenuBar: false
      }
    };
  },
  created() {
    this.getList();
    this.getAllAssetName();
  },
  methods: {
    /** 查询维修工单列表 */
    getList() {
      this.loading = true;
      const [startTime, endTime] = this.queryParams.timeRange || [];
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        ...(this.queryParams.assetName && { assetName: this.queryParams.assetName }),
        ...(startTime && { startTime }),
        ...(endTime && { endTime })
      };
      listRepairVo(params).then(response => {
        this.repairList = response.rows;
        this.total = response.total;
      }).catch(error => {
        console.error('查询维修列表失败：', error);
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 查询资产设备名称列表 */
    getAllAssetName() {
      getAllAssetName().then(response => {
        const data = response.data || [];
        this.uniqueAssetNames = data.map(item =>
          typeof item === 'object' ? item.assetName : item
        ).filter(Boolean);
      }).catch(error => {
        console.error('获取资产名称失败：', error);
        this.$modal.msgError('获取资产名称失败，请刷新重试');
      });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        repairId: null,
        assetId: null,
        faultInfo: {},
        repairExec: {},
        repairCheck: {},
        orderStatus: null,
        closeTime: null,
        fileUrls: null,
        remark: null
      };
      this.$refs.formRef?.clearValidate();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.repairId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修工单";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const repairId = row.repairId;
      getRepair(repairId).then(response => {
        const data = response.data;
        this.form = {
          ...data,
          faultInfo: this.safeParseJSON(data.faultInfo),
          repairExec: this.safeParseJSON(data.repairExec),
          repairCheck: this.safeParseJSON(data.repairCheck),
          fileUrls: this.formatFileUrlsForView(data.fileUrls)
        };
        this.open = true;
        this.title = "修改维修工单";
      }).catch(error => {
        console.error('获取维修详情失败：', error);
        this.$modal.msgError('获取详情失败，请重试');
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            faultInfo: JSON.stringify(this.form.faultInfo || {}),
            repairExec: JSON.stringify(this.form.repairExec || {}),
            repairCheck: JSON.stringify(this.form.repairCheck || {}),
            fileUrls: this.formatFileUrlsForApi(this.form.fileUrls)
          };

          const request = submitData.repairId ? updateRepair : addRepair;
          request(submitData).then(() => {
            this.open = false;
            this.$modal.msgSuccess(submitData.repairId ? "修改成功" : "新增成功");
            this.getList();
          }).catch(error => {
            console.error('提交失败：', error);
            this.$modal.msgError('操作失败，请重试');
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const repairIds = row ? [row.repairId] : this.ids;
      this.$modal.confirm(`确定要删除选中的 ${repairIds.length} 条记录吗？`).then(() => {
        return delRepair(repairIds);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('equ/repair/export', {
        ...this.queryParams
      }, `repair_${new Date().getTime()}.xlsx`);
    },

    /** 安全解析JSON */
    safeParseJSON(jsonString) {
      if (!jsonString || typeof jsonString !== 'string') {
        return {};
      }
      try {
        return JSON.parse(jsonString);
      } catch (e) {
        console.error('JSON解析失败：', e, '原始字符串：', jsonString);
        this.$modal.msgError('数据解析失败，请联系管理员');
        return {};
      }
    },

    /** 将后端返回的文件URL格式转换为前端显示格式 */
    formatFileUrlsForView(apiFormat) {
      if (!apiFormat) return null;
      try {
        const fileObj = JSON.parse(apiFormat);
        const key = Object.keys(fileObj)[0];
        if (key && Array.isArray(fileObj[key])) {
          // 假设后端返回的是完整URL，前端展示时去掉域名前缀
          const baseUrl = process.env.VUE_APP_BASE_URL || '';
          return fileObj[key].map(url => url.replace(new RegExp(`^${baseUrl}`), '')).join(',');
        }
      } catch (e) {
        console.error('【formatFileUrlsForView】解析附件格式失败：', e);
      }
      return apiFormat; // 如果解析失败，原样返回
    },

    /** 将前端表单的文件URL格式转换为API提交格式 */
    formatFileUrlsForApi(viewFormat) {
      if (!viewFormat) return '{}';
      try {
        const baseUrl = process.env.VUE_APP_BASE_URL || '';
        const urls = viewFormat.split(',').map(url => url.trim()).filter(url => url);
        // 简单处理，默认使用第一个键名或 'files'
        const defaultKey = 'files';
        return JSON.stringify({ [defaultKey]: urls.map(url => url.startsWith('http') ? url : `${baseUrl}${url}`) });
      } catch (e) {
        console.error('【formatFileUrlsForApi】格式化附件格式失败：', e);
        return '{}';
      }
    }
  }
};
</script>

<style scoped>
.view-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.view-form::-webkit-scrollbar {
  width: 8px;
}
.view-form::-webkit-scrollbar-track {
  background: #f1f1f1;
}
.view-form::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}
.view-form::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.json-editor {
  min-height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.clean-json-editor >>> .jsoneditor-menu,
.clean-json-editor >>> .jsoneditor-search,
.clean-json-editor >>> .jsoneditor-dragarea {
  display: none !important;
}
</style>
